package com.wb.mas.ui.auth;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.wb.mas.BR;
import com.wb.mas.R;
import com.wb.mas.app.AppViewModelFactory;
import com.wb.mas.databinding.ActAuthContactBinding;
import com.wb.mas.entity.DicInfoEntity;
import com.wb.mas.widget.OnPopitemClickLinstener;
import com.wb.mas.widget.SelectPopWindow;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthContactAc extends BaseActivity<ActAuthContactBinding, AuthContactViewModel> implements OnPopitemClickLinstener {

    private static final int PICK_CONTACT = 1;
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 2;
    private SelectPopWindow selectPopWindow;
    private Intent mIntent;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.act_auth_contact;
    }

    @Override
    public int initVariableId() {
        return BR.authContactViewModel;

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            Window window = getWindow();
//            // Translucent status bar
//            window.setFlags(
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }
    }

    @Override
    public AuthContactViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(AuthContactViewModel.class);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();


        viewModel.uc.showPopupEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                showDictPopUpWindow(viewModel.getCurrentDictType(), viewModel.getCurrentDictList());
            }
        });
        viewModel.uc.selectContact.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                selectConnection();
            }
        });


    }


    private void showDictPopUpWindow(String currentDictType, List<DicInfoEntity> currentDictList) {
        String titleName = getPopTitleName(currentDictType);
        List<String> itemStrList = new ArrayList<>();
        for (DicInfoEntity entity : currentDictList) {

            itemStrList.add(entity.getDictValue());
        }
        getPopUpWindow(itemStrList, titleName).show(this, itemStrList.get(0));
    }

    private String getPopTitleName(String currentDictType) {
        return getString(R.string.auth_pi_please_select_hint);
    }


    private SelectPopWindow getPopUpWindow(List<String> itemStrList, String titleName) {
//        if (selectPopWindow == null) {
        selectPopWindow = new SelectPopWindow(this, itemStrList, titleName);

        selectPopWindow.setOnPoPItemClickLinstener(this);
//        } else {
//        }

        return selectPopWindow;
    }

    @Override
    public void OnItemClick(String title, int position) {

        viewModel.onItemSelected(title, position);
        selectPopWindow.dismiss();

    }


    private void selectConnection() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, PICK_CONTACT);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PICK_CONTACT:
                mIntent = data;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                    //申请授权，第一个参数为要申请用户授权的权限；第二个参数为requestCode 必须大于等于0，主要用于回调的时候检测，匹配特定的onRequestPermissionsResult。
                    //可以从方法名requestPermissions以及第二个参数看出，是支持一次性申请多个权限的，系统会通过对话框逐一询问用户是否授权。
                    requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);

                } else {
                    //如果该版本低于6.0，或者该权限已被授予，它则可以继续读取联系人。
                    getContacts(data);
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户成功授予权限
                getContacts(mIntent);
            } else {
                ToastUtils.showShort(getString(R.string.app_pression_refuse));
            }
        }
    }


    private void getContacts(Intent data) {
        if (data == null) {
            return;
        }

        Uri contactData = data.getData();
        if (contactData == null) {
            return;
        }
        String name = "";
        String phoneNumber = "";

        Uri contactUri = data.getData();
        Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
        if (cursor.moveToFirst()) {
            name = cursor
                    .getString(cursor
                            .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String hasPhone = cursor
                    .getString(cursor
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            String id = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));
            if (hasPhone.equalsIgnoreCase("1")) {
                hasPhone = "true";
            } else {
                hasPhone = "false";
            }
            if (Boolean.parseBoolean(hasPhone)) {
                Cursor phones = getContentResolver()
                        .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                        + " = " + id, null, null);
                while (phones.moveToNext()) {
                    phoneNumber = phones
                            .getString(phones
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                phones.close();
            }
            cursor.close();


            viewModel.setUiNameAndNum(name, phoneNumber);
//            et_username.setText(name);
//            et_phone.setText(phoneNumber);
        }
    }

}
